<?php
namespace App\Controllers;

use App\Library\App;

class UploadController extends BaseController {

    public function initialize() {
        parent::initialize();
    }

    public function excelAction() {
        $filed = isset($_POST['filed']) ? $_POST['filed'] : 'file';
        if(!isset($_FILES[$filed])) {
            return $this->sendAjax(false, '上传错误，没有找到上传文件！');
        }
        $config   = App::globalConfig();
        $dir      = date('ym');
        $savePath = $config->excel_log_path;
        $savePath = rtrim($savePath, '/') . '/' . $dir . '/';
        if(!file_exists($savePath)) {
            if(!mkdir($savePath)) {
                return $this->sendAjax(false, '上传目录不存在！');
            }
        }
        if(is_dir($savePath) === false) {
            return $this->sendAjax(false, '上传目录不存在！');
        }
        if(is_writable($savePath) === false) {
            return $this->sendAjax(false, '上传目录权限错误！');
        }
        $info = pathinfo($_FILES[$filed]['name']);
        $ext  = strtolower($info['extension']);
        $exts = ['xlsx', 'xls', 'csv'];
        if(!empty($exts) && is_array($exts) && count($exts) > 0) {
            if(!in_array($ext, $exts)) {
                return $this->sendAjax(false, '上传错误，文件扩展名不被允许！');
            }
        } else {
            return $this->sendAjax(false, '上传错误，被允许上传的文件扩展名配置丢失！');
        }
        $newName  = date("dHis") . mt_rand(10, 99) . '.' . $ext;
        $savePath = $savePath . $newName;
        if(move_uploaded_file($_FILES[$filed]['tmp_name'], $savePath) === false) {
            return $this->sendAjax(false, '系统错误，上传文件失败！');
        }
        chmod($savePath, 0644);
        $this->sendAjax(true, $savePath);
    }
}
